package com.ibix.netty.communion;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;

/**
 * Created by Administrator on 2018/1/23.
 */
public class MyClientHandler extends ChannelInboundHandlerAdapter {
    private Logger logger;

    public MyClientHandler(Logger logger)
    {
        this.logger = logger;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageHandle.distributeMessage(ctx,msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接服务器成功");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.warn("与服务器的连接中断");
        MyClient.doConnect();
        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent e = (IdleStateEvent)evt;
            if(e.state() == IdleState.READER_IDLE){
                if(!ctx.channel().isActive()){
                    MyClient.doConnect();
                }
            }else if(e.state() == IdleState.WRITER_IDLE){
                MessageHandle.sendMessage(ctx,MessagePing.getMessagePing());
            }
        }
    }
}
